package cn.cqsztech.sort;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * 利用优先队列K个升序序链表合并
 * ccmars
 * 2022/3/15
 **/
public class MergeSortedLinkedList {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeSortedList(ListNode[] lists) {
        if (lists == null) {
            return null;
        }
        PriorityQueue<ListNode> temp = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });
        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) {
                temp.add(lists[i]);
            }
        }
        if (temp.isEmpty()) {
            return null;
        }
        ListNode head = temp.poll();
        ListNode pre = head;
        if (pre.next != null) {
            temp.add(pre.next);
        }
        while (!temp.isEmpty()) {
            ListNode current = temp.poll();
            pre.next = current;
            pre = current;
            if (current.next != null) {
                temp.add(current.next);
            }
        }
        return head;
    }

}
